import React, { useState, useEffect, useRef } from 'react';
import styles from './index.module.less';
import FormGroup from '@/components/form-group';
import { FormListItem } from '@/components/form-group/interface';
import StatusTag, { StatusTagProps } from '@/components/status-tag';
import classnames from 'classnames';
import {
  DocDetail,
  DeleteDoc,
  PublishEditDoc,
  EditDocumentCcUserList
} from '@/services/official-doc';
import { DOCUMENT_TYPE_MAP, OFFICIAL_APPLY_SCOPE_MAP } from '@/pages/official-doc/constants';
import Avatar from '@/components/avatar';
import ButtonFooterDetail from '@/components/button-footer-detail';
import { DocDetail as DocDetailType } from '@/pages/official-doc/interface.d';
import { Toast } from 'antd-mobile-v2';
import { SecondConfirm } from '@/components/second-confirm';
// import FileCardList from '@/components/file-card-list';
import { APPROVAL_STATUS } from '@/pages/declare/constants';
import ContractSelectModal from '@/components/ContractSelectModal';
import { useSelector } from 'react-redux';
import { DetailMatterCard } from '@/pages/official-doc/components/detail-matter-card';
import ProcessList from '@/components/ProcessList';
import { GetRucDraftAudit } from '@/services/laber-declare';
import { applyType } from '@/constants';
import history from '@/utils/history';
import { DEFAULT_CHOOSE_DIC } from '@/plugins/form/form-components/group-official/constants';
import { getSearchName } from '@/utils';
import { DOC_TYPE } from '@/pages/official-doc/components/log/index';

const OfficialDocDetail: React.FC<any> = (props) => {
  const formRef: React.MutableRefObject<any> = useRef();
  const docId = useRef(props.match.params.id);
  const [docDetail, setDocDetail] = useState({} as DocDetailType);
  const [formData, setFormData] = useState([] as FormListItem[]);
  const [selecterVisible, setSelecterVisible] = useState<boolean>(false);
  const [processFormData, setProcessFormData] = useState<any>();
  const [processDetailData, setProcessDetailData] = useState<any>();
  const [applyTypeFromUrl] = useState<any>(getSearchName('applyType'));
  const enterType = Number(getSearchName('enterType')); // 进入详情的入口类型
  const from = getSearchName('from'); // 从哪个页面来的

  const { orgTree } = useSelector((state: any) => ({
    orgTree: state.common.orgTree
  }));

  useEffect(() => {
    if (applyTypeFromUrl === applyType.ONLINE_DOCUMENT_APPLY) {
      sendGetProcessDetailRequest();
    }
    getDocDetail();
  }, []);

  useEffect(() => {
    docDetail && formatFormData(docDetail);
  }, [docDetail, selecterVisible]);

  const getDocDetail = async () => {
    const res = await DocDetail(docId.current);
    console.log('res----{}', res.data);
    if (res.data?.triScope) {
      res.data.triScopeInfo = res.data.triScope?.split(',');
    }
    setDocDetail(res.data);


    const procRecordId = res?.data?.procRecordId || '';
    if (from === 'declareDetail') {
      sendGetProcessDetailRequest(procRecordId);
    }
  };

  const sendGetProcessDetailRequest = async (id?: any) => {
    const procRecordId = getSearchName('procRecordId') || id;
    const param = {
      applyType: applyType.ONLINE_DOCUMENT_APPLY,
      dataId: docId.current,
      procRecordId: procRecordId
    };
    const res: any = await GetRucDraftAudit(param);
    if (res && res.status == 200) {
      if (!res.data?.processListRes?.formData) return;
      const { formModelData } = res.data?.processListRes?.formData;
      const detailData = {
        bizCrtTime: res.data?.bizCrtTime,
        bizCode: res.data?.bizCode,
        bizUserName: res.data?.processListRes?.formData?.startName,
        bizUserId: res.data?.processListRes?.formData?.startUserId,
        procStatusName: res.data?.processListRes?.procStatusName,
        bizStatus: res.data?.bizStatus,
        dataId: res.data?.dataId,
        innerProcDefId: res.data?.processListRes?.innerProcDefId,
        procRecordId: res.data?.processListRes?.procRecordId,
        procInstId: res.data?.processListRes?.procInstId,
        procName: res.data?.processListRes?.procName,
        procNo: res.data?.processListRes?.procNo,
        historyTask: res.data?.processListRes.historyTask,
        bizOrgId: res.data?.bizOrgId,
        srvTime: res.srvTime
      };
      setProcessFormData(formModelData);
      setProcessDetailData(detailData);
    }
  };

  const formatFormData = (data: any) => {
    console.log('data----{}', data);
    let result: FormListItem[] = [
      {
        label: '部门',
        valueKey: 'orgName',
        type: 'text',
        content: data.orgName
      },
      {
        label: '公文名称',
        valueKey: 'documentName',
        type: 'text',
        content: data.documentName
      },
      {
        label: '公文号',
        valueKey: 'documentCode',
        type: 'text',
        content: data.documentCode
      },
      {
        label: '签发人',
        valueKey: 'signName',
        type: 'text',
        content: data.signName
      },
      {
        label: '公文类型',
        valueKey: 'documentType',
        type: 'text',
        content: DOCUMENT_TYPE_MAP[data.documentType]?.label
      },
      {
        label: '会议日期',
        valueKey: 'meetingDate',
        type: 'text',
        content: data.meetingDate?.replace(/\s[\S]+/g, '')
      },
      {
        label: '主持人',
        valueKey: 'anchorName',
        type: 'text',
        content: data.anchorName
      },
      {
        label: '参会人员',
        valueKey: 'participantInfoList',
        type: 'text',
        content: data.participantInfoList
          ?.map((item: any) => item.userName)
          .join('，')
      },
      {
        label: '公文附件',
        valueKey: 'attachmentList',
        type: 'filePicker',
        cellProps: {
          renderMode: 'detail',
          receiveData: data.attachmentList
        }
      },
      {
        label: '抄送',
        valueKey: 'ccUserList',
        type: 'text',
        content: (
          <div className={styles.positionRelative}>
            {data.ccUserList?.map((item: any) => item.name)?.join('，')}
            {enterType !== DOC_TYPE.MY_RECEIVE && (
              <i
                className={classnames('icon iconfont', styles.editIcon)}
                onClick={toggleSelecter}
              >
                &#xe6ea;
              </i>
            )}
            <ContractSelectModal
              modalStatus={selecterVisible}
              closeModal={handleSelecterClose}
              submit={onCcUserListSubmit}
              resetData={formatCcUserList(data.ccUserList)} // 表单回填的数据，使用时参考公文录入功能的表单回填写法
              type="all"
              mode="multiple"
              orgData={orgTree}
              saveOnSubmit
            />
          </div>
        )
      },
      {
        label: '适用范围',
        valueKey: 'triScopeInfo',
        type: 'text',
        content: data.triScopeInfo
          ?.map((item: any) => {
            const label = OFFICIAL_APPLY_SCOPE_MAP[item]?.label;
            return label ? label : OFFICIAL_APPLY_SCOPE_MAP[item];
          })
          .join('，')
      },
      {
        label: '是否绩效方案',
        valueKey: 'isInvolvePerformance',
        type: 'text',
        content: DEFAULT_CHOOSE_DIC[data.isInvolvePerformance]
      }
    ];
    if (!applyTypeFromUrl) {
      // 线下公文类型去掉 '是否绩效方案' 项
      result = result.filter(
        (item: FormListItem) => item.valueKey !== 'isInvolvePerformance'
      );
    }
    setFormData(result);
  };

  const toggleSelecter = () => {
    setSelecterVisible(!selecterVisible);
  };

  const formatCcUserList = (list: any[] = []) => {
    return list.map((item: any) => ({
      text: item.name,
      type: item.userOrgType,
      value: item.id
    }));
  };

  const handleSelecterClose = () => {
    toggleSelecter();
  };

  const onCcUserListSubmit = async (_isHandle, selectArray) => {
    const data = {
      id: docDetail.id,
      ccUserList: selectArray.map((item: any) => ({
        id: item.key,
        name: item.title,
        userOrgType: item.type
      }))
    };
    const res = await EditDocumentCcUserList(data);
    if (res.status === 200) {
      Toast.info('修改成功');
      getDocDetail();
      toggleSelecter();
    } else {
      Toast.info('修改失败');
    }
  };

  const getStatusTagProps = (status: number): StatusTagProps => {
    let result: StatusTagProps;
    if (status === 2) {
      result = { text: '已通过', type: 'success' };
    } else {
      result = { text: '草稿', type: 'cancel' };
    }
    return result;
  };

  const handleDelete = async () => {
    const params = {
      buttons: [
        {
          text: '删除',
          cb: async () => {
            const res = await DeleteDoc(docDetail.id);
            if (res.status === 200) {
              Toast.info('删除成功');
              props.history.goBack();
            }
          }
        },
        {
          text: '取消'
        }
      ],
      message: '确认删除？'
    };
    SecondConfirm(params);
  };

  const handleEdit = () => {
    if (applyTypeFromUrl === applyType.ONLINE_DOCUMENT_APPLY) {
      return history.push({
        pathname: '/resubmit',
        query: {
          applyType: applyTypeFromUrl,
          applyId: docId.current,
          innerProcDefId: processDetailData?.innerProcDefId,
          status: processDetailData?.bizStatus,
          resubmit: false,
          title: `${processDetailData?.bizUserName}的线上公文签批`,
          orgId: processDetailData?.bizOrgId,
          procRecordId: processDetailData?.procRecordId
        }
      });
    }
    history.push(`/official-doc/edit/${docDetail.id}`);
  };

  const handlePublish = async () => {
    const data = { ...docDetail };
    const res = await PublishEditDoc(data);
    if (res.status === 200) {
      Toast.info('发布成功');
      history.replace('/official-doc/2');
    }
  };

  const getButtonOptions = () => {
    const deleteBtn = {
      text: '删除',
      icon: <i className="iconfont icon">&#xe6e0;</i>,
      onClick: handleDelete
    };
    const editBtn = {
      text: '修改',
      icon: <i className="iconfont icon">&#xe6ea;</i>,
      onClick: handleEdit
    };
    const publishBtn = {
      text: '发布',
      icon: <i className="iconfont icon">&#xe6e9;</i>,
      onClick: handlePublish
    };
    if (enterType === DOC_TYPE.MY_RECEIVE) {
      // 来自我的收文页面时，不支持操作
      return [];
    } else if (docDetail.status === APPROVAL_STATUS.Draft) {
      return [deleteBtn, editBtn, publishBtn];
    } else if (
      docDetail.status === APPROVAL_STATUS.Pass &&
      applyTypeFromUrl === applyType.ONLINE_DOCUMENT_APPLY
    ) {
      // 线上公文详情，无操作
      return [];
    } else if (
      docDetail.status === APPROVAL_STATUS.Pass &&
      docDetail.isRelatedFlow === 1
    ) {
      // 1-未关联流程 1-已关联流程
      return [deleteBtn, editBtn];
    }
    return [];
  };

  return (
    <div className={styles.wrap}>
      <div className={styles.title}>
        <div className={styles.avatar}>
          <Avatar name={docDetail?.crtUserName} />
        </div>
        <p className={styles.titleText}>{docDetail?.documentName}</p>
        <StatusTag {...getStatusTagProps(docDetail?.status)} />
      </div>
      <div className={styles.formWrap}>
        <FormGroup ref={formRef} formList={formData} />
      </div>
      <DetailMatterCard
        list={docDetail?.matterAddList || []}
        editMember={enterType === DOC_TYPE.MY_RECEIVE ? false : true}
        onSubmit={getDocDetail}
      />
      {processFormData ? (
        <div className={styles.applyFormProcess}>
          {
            <ProcessList
              className={styles.processList}
              historyTask={processDetailData?.historyTask || []}
              renderMode="detail"
              srvTime={processDetailData?.srvTime}
            />
          }
        </div>
      ) : null}
      {getButtonOptions()?.length ? (
        <ButtonFooterDetail data={getButtonOptions()} />
      ) : null}
    </div>
  );
};

export default OfficialDocDetail;
